<template>
  <div class="note-detail" v-if="note">
    <div class="box-header">
     <div>
      <el-icon @click="goOut()"><ArrowLeftBold /></el-icon>
         <!-- 笔记标题 -->
      <h2 class="note-title" v-if="note.title">{{ note.title }}</h2>
     </div>
    </div>
    <div class="box-subhead">
    <!-- 用户信息 -->
    <div class="note-user">
      <el-avatar :size="50" :src="note.user.avatar_url || defaultAvatar" />
      <span class="user-name">{{ note.user.username }}</span>
    </div>
     <!-- 标签列表 -->
    <div class="note-tags" v-if="note.category_readable">
        <span>{{note.category_readable.name}}</span>
    </div>
    <!-- 标签列表 -->
    <div class="note-tags" v-if="note.tags_readable">
      <el-tag v-for="tag in note.tags_readable" :key="tag" class="note-tag">{{ tag }}</el-tag>
    </div>
    <div>
      {{formatTime(note.created_at) }}
    </div>
    </div>
    <!-- 笔记封面 -->
    <el-image v-if="note.cover_image_url" :src="note.cover_image_url" fit="cover" class="note-cover" />

    <!-- 笔记内容 -->
    <MdCatalog :editorId="id" :scrollElement="scrollElement" :theme="theme" class="directory" />
    <MdPreview :editorId="id" :modelValue="note.content" :theme="theme" :previewTheme="'github'" />

  <!-- 点赞功能 -->
    <div class="note-stats">
      <div class="like-comment-wrapper">
        <!-- 点赞 -->
        <span @click="toggleLike" class="like-count">
          <span v-if="!note.liked_by_user" class="like-icon liked">
            <good-two theme="multi-color" size="30" :fill="['rgba(0,0,0,0.52)' ,'#ffffff' ,'#ffffff' ,'#ffffff']" />
          </span>
          <span v-else class="like-icon not-liked">
            <good-two theme="multi-color" size="30" :fill="['#333' ,'#f8e71c' ,'#ffffff' ,'#ffffff']" />
          </span>
          <span class="like-text">{{ note.like_count }}</span>
        </span>

        <!-- 评论 -->
        <a  href="#comment">
        <span class="comment-count">
          <comment-one theme="multi-color" size="30" :fill="['#7654ce' ,'#4a90e2' ,'#ffffff' ,'#ffffff']" />
          <span class="comment-text">{{ note.comments_count }}</span>
        </span>
        </a>
      </div>
    </div>
    <!-- 使用 Undraw UI 评论组件 -->
    <u-comment id="comment" :config="commentConfig" @submit="submitComment" />

    <!-- 回到顶部按钮 -->
    <el-button v-if="showBackToTop" @click="scrollToTop" class="back-to-top" type="primary" icon="Top"></el-button>
  </div>
</template>

<script setup lang="ts">
// 下载表情包资源 emoji.zip，并引入 emoji.ts 文件
import emoji from '@/assets/emoji' // 使用你自己的表情包路径
import { reactive, ref, onMounted, watch, onBeforeUnmount } from 'vue'
import {useRoute, useRouter} from 'vue-router'
import { getAction, postAction } from '@/api/manage'
import { Data } from '@/api/ajaxUrl.config'
import defaultAvatar from '@/assets/img/default_avatar.png'
import { MdPreview, MdCatalog } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import { useDark } from '@vueuse/core'
import { Time, UToast, CommentApi, CommentSubmitApi, ConfigApi } from 'undraw-ui'
import {GoodTwo,CommentOne } from '@icon-park/vue-next';
import {ArrowLeftBold} from "@element-plus/icons-vue";
import {formatTime} from "@/utils/utils";

const id = 'preview-only'
const scrollElement = document.documentElement
const route = useRoute()
const router = useRouter()
const note = ref(null) // 当前笔记详情
const showBackToTop = ref(false)
const theme = ref(useDark().value ? 'dark' : 'light')

// 监听主题切换
watch(useDark(), (newValue) => {
  theme.value = newValue ? 'dark' : 'light'
})

// 返回事件
const goOut = ()=>{
  router.back();
}


// 评论配置
const commentConfig = reactive<ConfigApi>({
  user: {} as any, // 当前用户信息
  emoji: emoji, // 表情包数据
  comments: [], // 评论数据
  relativeTime: false, // 开启人性化时间
  show: {
    level: false,    // 关闭等级显示
    homeLink: false, // 关闭个人主页链接跳转
    address: false,  // 关闭地址信息
    likes: false     // 关闭点赞按钮显示
  }
})

// 获取笔记详情
const fetchNoteDetail = () => {
  const noteId = route.params.id
  getAction(`${Data.notes}${noteId}/`, '').then((res: any) => {
    note.value = res
    // 需要重新配置用户信息
    commentConfig.user = {
      id: note.value.user.id,
      username: note.value.user.username,
      avatar: note.value.user.avatar_url || defaultAvatar
    }
  })
}

// 获取评论数据
const fetchComments = () => {
  const noteId = route.params.id
  let  params = {
    note_id: noteId
  }
  getAction(`${Data.comments}`, params).then((res: any) => {
    commentConfig.comments = res.results.map((comment: any) => ({
      id: comment.id,
      parentId: comment.parent ? comment.parent.id : null,
      uid: comment.user.id,
      content: comment.content,
      likes: comment.likes,
      createTime: new Time(comment.createTime).toString(),
      user: {
        id: comment.user.id,
        username: comment.user.username,
        avatar: comment.user.avatar || defaultAvatar,
      },
      reply: comment.reply? {
        total: comment.reply.length,
        list: comment.reply.list.map((reply: any) => ({
          id: reply.id,
          parentId: reply.parent ? reply.parent.id : null,
          uid: reply.user.id,
          content: reply.content,
          likes: reply.likes,
          createTime: new Time(reply.createTime).toString(),
          user: {
            id: reply.user.id,
            username: reply.user.username,
            avatar: reply.user.avatar_url || defaultAvatar,
          }
        }))
      } : null
    }))
  })
}

// 提交评论
const submitComment = ({ content, parentId, finish }: CommentSubmitApi) => {
  const noteId = route.params.id
  const data = {
    content,
    parentId: parentId || null,
    note_id: noteId,
  }

  postAction(Data.comments, data).then((response: any) => {
    // 模拟返回生成的评论
    const newComment: CommentApi = {
      id: String(Date.now()),
      parentId: parentId || null,
      uid: commentConfig.user.id,
      content: content,
      createTime: new Time().toString(),
      user: {
        username: commentConfig.user.username,
        avatar: commentConfig.user.avatar
      },
      reply: null
    }

    // 更新评论列表
    commentConfig.comments.push(newComment)
    finish(newComment) // 完成回调
    UToast({ message: '评论成功!', type: 'info' })
  })
}

// 点赞功能
const toggleLike = () => {
  const noteId = route.params.id
  if (note.value?.liked_by_user) {
    postAction(`${Data.notes}/${noteId}/likes/`, {}).then(() => {
      note.value.like_count -= 1
      note.value.liked_by_user = false
    })
  } else {
    postAction(`${Data.notes}/${noteId}/likes/`, {}).then(() => {
      note.value.like_count += 1
      note.value.liked_by_user = true
    })
  }
}

// 回到顶部按钮
const handleScroll = () => {
  showBackToTop.value = window.scrollY > 300
}

const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
}

onMounted(() => {
  fetchNoteDetail()  // 获取文章详情
  fetchComments()    // 获取评论列表
  window.addEventListener('scroll', handleScroll)
})

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped lang="less">
.box-subhead{
  display: flex;
  align-items: center;
  margin-bottom: 20px ;
  >*{
    margin-right: 20px;
  }
}
.box-header{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  >div{
    &:nth-of-type(1){
      display: flex;
      align-items: center;
      .el-icon{
        font-size: 20px;
        margin: 0 10px;
        cursor: pointer;
        &:hover{
          color: #a8b1ff;
        }
      }
  }
  }

}
.note-detail {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  position: relative;
}

.note-title {
  font-size: 28px;
  font-weight: bold;
}

.note-user {
  display: flex;
  align-items: center;
}

.user-name {
  margin-left: 10px;
  font-size: 16px;
}

.note-cover {
  width: 100%;
  height: 300px;
  margin-bottom: 20px;
  border-radius: 10px;
}

.note-stats {
  position: fixed;
  bottom: 30px;
  left:20px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  background: var(--color-border-hover);
  padding: 5px;
  border-radius: 10px;
  width: 100%;
  max-width: 170px;
}

.like-comment-wrapper {
  display: flex;
  gap: 20px;
  align-items: center;
}

.like-count,
.comment-count {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.like-count:hover,
.comment-count:hover {
  transform: scale(1.1); /* 鼠标悬停时放大 */
}

.like-icon,
.comment-icon {
  margin-right: 8px;
}

.like-text,
.comment-text {
  font-size: 18px;
  font-weight: bold;
  margin-left: 6px;
}

.liked {
  color: #ff4757; /* 点赞后的颜色 */
}

.not-liked {
  color: #333; /* 未点赞时的颜色 */
}

.back-to-top {
  position: fixed;
  bottom: 50px;
  right: 30px;
  z-index: 1000;
  background-color: #0073e6;
  color: white;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.back-to-top:hover {
  background-color: #005bb5;
}


//屏幕适配
/* 针对大屏设备 (桌面显示器) */
@media (min-width: 1400px) {
  /* 大屏样式 */
  .directory{
    position: fixed;
    top:150px;
    right: 20px;
    z-index: 999;
  }
}

/* 针对中屏设备 (平板) */
@media (min-width: 768px) and (max-width: 1199px) {
  /* 中屏样式 */
}

/* 针对小屏设备 (手机) */
@media (max-width: 767px) {
  /* 小屏样式 */
}


</style>
